const app = getApp();
const { isAuthGetLocation, getLocationInfo, navTo, showLoading, hideLoading, getExtInfo } = require('../../common/platform');
const { matchAddress } = require('../../api/main');
const { HOME_CONTENT_TYPE, SHOP_MODE_TYPE } = require('../../constants/types');
const { PAGE_NAV } = require('../../constants/route');
const { getTabbarShowIndex } = require('../../biztools/main');
const { setMode, setStyleMode, setTheme, setLocationValue, setLocationFailFlag, getLocationValue, getUserToken } = require('../../biztools/info');
const { getShopConfig, getShopSetting, getShopStoreShelfList, getLiveRoomId } = require('../../api/shop');
const { isValidTime } = require('../../common/utils');
const { PageBase } = require('../../mixins/page');

Page({
    mixins: [PageBase],
    data: {
        vtabs: [],
        activeTab: 0,
        locationFail: true,
        locationInfo: null,
        isCancChangeLocation: false,
        global: {},
        tabbar: null,
        home: {},
        storeList: [],
        homeContentType: HOME_CONTENT_TYPE,
        activeIndex: 0, // tab-bar 选中
        showStartPage: false,
        showStartPicture: '',
        isPageConfigReady: false,
        // 直播
        roomId: '',
        isRedirect: false,
        orderNumber: '',
    },
    async onLoad(options) {
        const { shopOrderNumber } = options;
        if (shopOrderNumber) {
            this.setData({
                isRedirect: true,
                orderNumber: shopOrderNumber,
            });
        }
        // 获取装修信息
        await this._getBrandConfig();
    },
    async onShow() {
        this.refreshTabbarIndex();
        // 获取直播中的直播间
        const roomId = await getLiveRoomId();
        this.setData({
            roomId,
        });
        const { isNeedRefreshAddress } = app.globalData;
        if (isNeedRefreshAddress) {
            await this.getGeoInfo();
            app.globalData.isNeedRefreshAddress = false;
        }
        
    },
    async getGeoInfo () {
        const { isLogin, isUserChooseAddress } = app.globalData
        if (!isLogin) {
            setTimeout(async () => await this.getGeoInfo(), 200);
            return;
        }
        let locationFail = true;
        const _locationInfo = getLocationValue();
        // 获取定位信息
        const locationInfo = isUserChooseAddress ? _locationInfo : await getLocationInfo();
        let info;
        if (locationInfo) {
            const { latitude, longitude } = locationInfo;
            showLoading('匹配地址');
            console.log('Home => 获取的地址信息为：', locationInfo);
            info = await matchAddress(latitude, longitude);
            console.log('Home => 匹配的地址为：', info);
            setLocationValue({
                name: info.address,
                address: info.address,
                latitude,
                longitude,
            });
            locationFail = false;
            hideLoading();
        }
        setLocationFailFlag(locationFail);
        this.setData({
            locationFail,
            locationInfo: info,
        }, async () => {
            if (!locationFail) {
                const { latitude, longitude } = locationInfo;
                await this.getBaseInfo(latitude, longitude);
            }
            this.redirectAction();
        });
    },
    redirectAction() {
        const { isRedirect, orderNumber } = this.data;
        if (isRedirect) {
            this.setData({
                isRedirect: false,
                orderNumber: '',
            }, () => {
                navTo(PAGE_NAV.orderDetail, {
                    orderNumber,
                })
            });
        }
    },
    // 获取装修信息
    async _getBrandConfig() {
        const { isLogin } = app.globalData
        if (!isLogin) {
            setTimeout(async () => await this._getBrandConfig(), 200);
            return;
        }
        const shopConfig = await getShopConfig();
        await this.saveGlobalConfig(shopConfig);
    },

    async getBaseInfo(latitude, longitude) {
        const { config } = app.globalData;
        showLoading('加载中...');
        // 获取配置信息
        const shopSetting = await getShopSetting(latitude, longitude);
        this.saveGlobalSetting(shopSetting);
        await this.saveBrandInfo(config, shopSetting);
        hideLoading();
    },
    async saveGlobalConfig(config) {
        const { isShowedStartPage } = app.globalData;
        const { mode, style, theme } = config.global;
        const { isOpen, picture, startTime, endTime, showTime } = config.startPage;
        wx.setNavigationBarTitle({
            title: config.brandName//页面标题为品牌名称
        })
        setMode(mode);
        setStyleMode(style)
        setTheme(theme);
        app.globalData.config = config;
        let showStartPage = false;
        if (isOpen && isValidTime(startTime, endTime) && !isShowedStartPage) {
            showStartPage = true;
        }
        this.setData({
            global: config.global,
            tabbar: config.tabbar,
            home: config.home,
            showStartPage,
            showStartPicture: picture,
            isPageConfigReady: true,
        }, () => this.refreshTabbarIndex());
        if (showStartPage) {
            app.globalData.isShowedStartPage = true;
            setTimeout(async () => {
                this.setData({
                    showStartPage: false,
                });
                await this.getGeoInfo();
            }, showTime);
        } else {
            await this.getGeoInfo();
        }
    },
    async saveGlobalSetting(setting) {
        app.globalData.setting = setting;
        const { pages } = setting;
        let storeList = [];
        if (pages.length > 0) {
            storeList = await getShopStoreShelfList(pages);
        }
        console.log('数据为', setting.operation_mode, SHOP_MODE_TYPE.dealer,)
        this.setData({
            storeList,
            isCancChangeLocation: setting.operation_mode != SHOP_MODE_TYPE.dealer,
        });
    },
    async saveBrandInfo(config, setting) {
        const { brandName } = config;
        const extInfo = await getExtInfo();
        app.globalData.brandInfo = {
            id: extInfo.brand_id,
            name: brandName,
            operationMode: setting.operation_mode,
            allowBooking: setting.allow_booking,
            bookingDays: setting.booking_days,
        };
    },
    refreshTabbarIndex() {
        const { tabbar } = this.data;
        if (!tabbar) return;
        const activeIndex = getTabbarShowIndex(tabbar.list, 'home');
        this.setData({
            activeIndex,
        });
    },
    // 跳转到选择地址
    gotoSelectAddress() {
        const { isCancChangeLocation } = this.data;
        if (!isCancChangeLocation) return;
        navTo(PAGE_NAV.addressSelect);
    },
});